package com.sky.zuor;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sky.zuor.ent.FundsInfoResponse;
import lombok.Data;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class ZuoruiLoginAndxingu {
    //    public static final String base = "https://openapibk.zr.hk";
    public static final String base = "https://openapi8.zr66.com";
    //public static final String Key = "XqnAALej6kTWXPGnDBT+30SWHehhNuj6EDWhd+FNsZM=";
//    public static final String password = "!zVYU7P4zFAA$TUM";


    public static void main(String[] args) throws Exception {
        //接口调用顺序
        //1.平台登录
        // 生成当前时间戳（单位：秒）
        ZuoruiLoginAndxingu zuor = new ZuoruiLoginAndxingu();
        long timestamp = System.currentTimeMillis();
        String LoginPassword = "abcd1234";
        String secretKey = "C6RCkFFnxWFkT8kqd6+TeVWzSW5nrL6w28YRhpoiawg=";
        String loginEncrypted = LoginUtils.encrypt(LoginPassword, secretKey, timestamp);
        String TradePassword = "abc123";

        LoginResponse loginResponse = zuor.login(String.valueOf(UUID.randomUUID()), "iPhone 14", "iPhone",
                "18879153255", "86", loginEncrypted,
                timestamp);

        String clientId = loginResponse.getData().getClientId();
        String token = loginResponse.getData().getToken();
        System.out.println("clientId = " + clientId);

        //2.交易登录
        String TrageEncrypted = LoginUtils.encrypt(TradePassword, secretKey, timestamp);
        ResponseData responseData = zuor.tradeLogin(clientId, TrageEncrypted, token);
        System.out.println("responseData = " + responseData);
        //3.其他

        IpoResponse ipoInfo = zuor.getIpoInfo("00700", token,"HK");
        System.out.println("ipoInfo = " + ipoInfo);

//        FundsInfoResponse fundsInfo = getFundsInfo(token);
//        System.out.println("fundsInfo = " + fundsInfo);
    }


    public LoginResponse login(String deviceId, String deviceModel, String deviceName,
                               String phone, String phoneArea, String password, Long timestamp) throws Exception {

        // 创建 LoginVo 对象
        LoginVo loginVo = new LoginVo();
        loginVo.setPhone(phone);
        loginVo.setPhoneArea(phoneArea);
        loginVo.setPassword(password);
        loginVo.setTimestamp(timestamp);

        Gson gson = new GsonBuilder().create();
        // 转换 LoginVo 为 JSON
        String jsonBody = gson.toJson(loginVo);

        OkHttpClient client = new OkHttpClient();
        // 创建请求体
        RequestBody requestBody = RequestBody.create(jsonBody, MediaType.parse("application/json"));

        // 创建请求
        Request request = new Request.Builder()
                .url(base + "/client/login") // 替换为实际的服务器地址
                .post(requestBody)
                .addHeader("deviceId", deviceId)
                .addHeader("deviceModel", deviceModel)
                .addHeader("deviceName", deviceName)
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 处理响应
            String responseData = response.body().string();
            System.out.println("Response: " + responseData);

            // 将响应解析为 LoginResponse 对象
            LoginResponse loginResponse = gson.fromJson(responseData, LoginResponse.class);

            // 如果有响应数据，直接获取
            return loginResponse;
        }
    }

    @Data
    public  class LoginVo {
        private String phone;
        private String phoneArea;
        private String password;
        private Long timestamp;
    }

    @Data
    public  class LoginResponse {
        private String code; // 错误码
        private String msg; // 异常描述
        private LoginResponseData data; // 包含其他详细信息
    }

    @Data
   public class LoginResponseData {
        private String clientId; // 客户Id
        private String zrNo; // 卓锐号
        private String userName; // 用户名称
        private String phoneArea; // 手机区号
        private String phone; // 手机号
        private Integer accountType; // 用户注册类型: 1-个人户, 2-公司户
        private String token; // token
    }

    public ResponseData tradeLogin(String clientId, String password, String token) throws IOException {
        // 生成当前时间戳（单位：秒）
        long timestamp = System.currentTimeMillis();
        // 创建 TradeLoginVo 对象
        TradeLoginVo tradeLoginVo = new TradeLoginVo();
        tradeLoginVo.setClientId(clientId);
        tradeLoginVo.setPassword(password);
        tradeLoginVo.setTimestamp(timestamp);
        Gson gson = new GsonBuilder().create();
        // 转换 TradeLoginVo 为 JSON
        String jsonBody = gson.toJson(tradeLoginVo);

        // 创建请求体
        RequestBody requestBody = RequestBody.create(jsonBody, MediaType.parse("application/json"));

        // 创建请求
        Request request = new Request.Builder()
                .url(base + "/client/tradeLogin") // 替换为实际的服务器地址
                .post(requestBody)
                .addHeader("token", token)
                .build();
        OkHttpClient client = new OkHttpClient();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 处理响应
            String responseData = response.body().string();
            System.out.println("Response: " + responseData);
            // 解析响应 JSON（如果需要）
            ResponseData responseDataObject = gson.fromJson(responseData, ResponseData.class);
            // 处理响应数据
            return responseDataObject;
        }
    }

    @Data
    public class TradeLoginVo {
        private String clientId;  // 客户编号
        private String password;   // 交易密码
        private Long timestamp;     // 时间戳
    }

    // 响应数据类示例
    @Data
    public class ResponseData {
        private String code;
        private String msg;
        private String data;
    }






    public IpoResponse getIpoInfo(String code, String token,String ts) throws Exception {
        // 创建请求参数对象
        IpoRequestVO requestVo = new IpoRequestVO();
        requestVo.setTs(ts);
//        requestVo.setTs("US");
        requestVo.setCode(code);

        Gson gson = new GsonBuilder().create();
        // 转换请求参数为 JSON
        String jsonBody = gson.toJson(requestVo);

        OkHttpClient client = new OkHttpClient();

        // 创建请求体
        RequestBody requestBody = RequestBody.create(jsonBody, MediaType.parse("application/json"));

        String lang = "zh_CN";
        // 创建请求
        Request request = new Request.Builder()
                .url(base + "/ipo/ipo_info") // 替换为实际的服务器地址
                .post(requestBody)
                .addHeader("lang", lang) // 添加语言参数到请求头
                .addHeader("token", token) // 添加语言参数到请求头
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 处理响应
            String responseData = response.body().string();
            System.out.println("Response: " + responseData);

            // 将响应解析为 IpoResponse 对象
            return gson.fromJson(responseData, IpoResponse.class);
        }
    }


    @Data
    public static class IpoRequestVO {
        private String ts;
        private String code; // 股票代码
    }

    @Data
    public class IpoResponseData {
        private String name; // 证券名称
        private String nameCn; // 证券简体名称
        private String nameTw; // 证券繁体名称
        private Integer volunit; // 每手股数
        private Double minPrice; // 最低发售价
        private Double maxPrice; // 最高发售价
        private Double finalPrice; // 最终申购价
        private Long endTime; // 截至认购日期
        private Double entranceFee; // 入场费
        private Double handlingFee; // 现金认购手续费
        private Boolean favor; // 是否是优选
        private String analyzeUrl; // 分析的url
        private Double financingHandlingFee; // 融资认购手续费
        private Double compFinancingBalance; // 公司融资额度净余
        private String stopFinancingFlag; // 暂停融资申购
        private Double ipoIntrate; // 融资利率
        private Integer financingDays; // 融资天数
        private Double financingRatio; // 融资比例
        private Long systemTime; // 系统时间
        private Long ecashEndDateTime; // 网上现金申购截止日
        private Long efinancingEndDateTime; // 网上融资申购截止日
        private Long depositDate; // 返款日期
        private Double taxesFee; // 税费
        private List<String> labelNames; // 新股标签
        private Long syncTime; // 同步时间
        private List<IpoQty> ipoQtys; // 认购股数档位信息
    }

    @Data
    public class IpoQty {
        private Double applyBalance; // 申购金额
        private Integer applyQty; // 申购数量
        private List<FinancingRatio> financingRatios; // 融资比例
    }


    public static IpoPurResponse purchaseIpo(IpoPurVO ipoPurVO,String token) throws IOException {
        Gson gson = new GsonBuilder().create();
        // 将请求数据转为 JSON
        String json = gson.toJson(ipoPurVO);

        // 创建请求
        Request request = new Request.Builder()
                .url(base + "/ipo/pur") // 替换为实际的服务器地址
                .post(RequestBody.create(json, MediaType.parse("application/json")))
                .addHeader("token", token)
                .build();

        OkHttpClient client = new OkHttpClient();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 处理响应
            String responseData = response.body().string();
            System.out.println("Response: " + responseData);

            // 将响应解析为 IpoPurResponse 对象
            return gson.fromJson(responseData, IpoPurResponse.class);
        }
    }

    @Data
    public static class IpoPurVO {
        private String ts;              // 股票市场
        private String code;            // 股票代码
        private double applyQty;        // 申购数量
        private int actionIn;           // 操作类型。1：申购，2: 修改，3：撤销
        private Double financingRatio;   // 融资比例（可选）

        // Getters and Setters
    }

    @Data
    public class IpoPurResponse {
        private String code; // 错误码
        private String msg;  // 异常描述
        private String data; // 响应数据（如有）

        // Getters and Setters
    }




    public static IpoPurRecordResponse  queryIpoPurRecord(String lang, IpoRequestVO requestVO, String token) throws IOException {
        // 创建请求
        Gson gson = new GsonBuilder().create();
        Request request = new Request.Builder()
                .url(base + "/ipo/pur_record_detail_list") // 替换为实际的服务器地址
                .addHeader("lang", lang) // 添加请求头
                .addHeader("token", token)
                .post(RequestBody.create(gson.toJson(requestVO), MediaType.parse("application/json")))
                .build();

        OkHttpClient client = new OkHttpClient();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 处理响应
            String responseData = response.body().string();
            System.out.println("Response: " + responseData);

            // 将响应解析为 IpoPurRecordResponse 对象
            return gson.fromJson(responseData, IpoPurRecordResponse.class);
        }
    }
    @Data
    public class IpoPurRecordResponse {
        private String code; // 错误码
        private String msg;  // 异常描述
        private List<IpoPurRecord> data; // 申购记录

        // Getters and Setters
    }

    @Data
    public class IpoPurRecord {
        private String exchangeType;           // 市场类别
        private String ts;                     // 交易市场
        private String code;                   // 股票代码
        private String name;                   // 股票名称
        private double applyQty;               // 认购数量
        private String moneyType;              // 币种
        private double applyBalance;           // 申购金额
        private String status;                 // 申购详情状态
        private String statusCheck;            // 申购批核状态
        private double handlingFee;            // 手续费
        private double allottedQty;            // 已中签数量
        private String applyDatetime;          // 申购时间
        private long closeTime;                // 认购截止时间
        private long ecashEndDateTime;        // 网上现金申购截止日
        private long efinancingEndDateTime;   // 网上融资申购截止日
        private int financingType;             // 融资类型
        private int volunit;                   // 每手股数
        private double financingInterest;      // 融资利息
        private double financingRatio;         // 融资比例
        private double minPrice;               // 最低发售价
        private double maxPrice;               // 最高发售价
        private double compFinancingBalance;   // 公司融资额度净余
        private String stopFinancingFlag;      // 暂停融资申购
        private double ipoIntrate;             // 融资利率
        private int financingDays;             // 融资天数
        private double financingAmount;        // 融资金额
        private double selfPayAmount;          // 自缴金额
        private String depositDate;            // 公布日期(返款日)

        // Getters and Setters
    }



    public static FundsInfoResponse getFundsInfo(String token) throws IOException {
        // 创建请求
        Request request = new Request.Builder()
                .url(base + "/funds/info") // 替换为实际的服务器地址
                .post(RequestBody.create("", MediaType.parse("application/json"))) // POST请求体为空
                .addHeader("token", token) // 添加语言参数到请求头
                .build();
        OkHttpClient client = new OkHttpClient();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 处理响应
            String responseData = response.body().string();
            System.out.println("Response: " + responseData);
            Gson gson = new GsonBuilder().create();
            // 将响应解析为 FundsInfoResponse 对象
            return gson.fromJson(responseData, FundsInfoResponse.class);
        }
    }



    @Data
    public class FinancingRatio {
        private Double lever; // 杠杆倍数
        private Double ratio; // 比例
        private Double minFinancingBalance; // 最小融资金额
        private Double maxFinancingBalance; // 最大融资金额
    }

    @Data
    public class IpoResponse {
        private String code; // 错误码
        private String msg; // 异常描述
        private List<IpoResponseData> data; // 响应数据
    }


}


